<template>
  <div id="calendar" class="container mx-auto">
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
      <!-- 日历视图 -->
      <div class="lg:col-span-3 space-y-6">
        <div
          class="bg-white rounded-xl shadow-card p-5 hover:shadow-card-hover transition-all duration-300 animate-fade-in transform hover:-translate-y-1">
          <div class="overflow-x-auto">
            <el-calendar v-model="currentDate" :first-day-of-week="1">
              <template #dateCell="{ date, data }">
                <div class="calendar-day" :class="{ 'has-event': hasEvent(data.day), 'weekend': isWeekend(data.day) }">
                  <div class="day-number-container">
                    <div class="day-number"
                         :class="{ 'current-day': isCurrentDay(data.day), 'other-month': isOtherMonth(data.day) }">
                      {{ getDate(data.day) }}
                    </div>
                    <span v-if="hasEvent(data.day)" class="event-dot"></span>
                  </div>
                  <div class="day-events" v-if="hasEvent(data.day)">
                    <div v-for="item in getEventsByDate(data.day)" class="event" :key="item.id">

                      <el-popover
                        placement="right"
                        :title="title"
                        width="300"
                        trigger="click">

                        <el-form :ref="'remindFrom' + item.id " :model="formData" :rules="rules" size="mini" label-width="100px">
                          <el-form-item label="提醒内容" prop="message">
                            <el-input v-model="formData.message" placeholder="请输入提醒内容" clearable :style="{width: '100%'}">
                            </el-input>
                          </el-form-item>
                          <el-form-item label="触发时间" prop="remindTime">
                            <el-date-picker type="datetime" v-model="formData.remindTime" format="yyyy-MM-dd HH:mm:ss"
                                            value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择触发时间" clearable>
                            </el-date-picker>
                          </el-form-item>
                          <el-form-item>
                            <el-button size="mini" type="primary" @click="submitForm(item)">提交</el-button>
                            <el-button size="mini" @click="resetForm(item)">重置</el-button>
                          </el-form-item>
                        </el-form>

                        <div slot="reference" :class="`event-${item.color}`" @click="handleRemind(item)"> {{ item.title }} </div>
                      </el-popover>


                    </div>
                  </div>
                </div>
              </template>
            </el-calendar>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addSituation, getDateAll, getSituationById, updateSituation } from '@/api/dates/date'

export default {
  name: 'CalendarView',
  data () {
    return {
      currentDate: new Date(),
      events: [],
      formData: {
        message: undefined,
        remindTime: null,
      },
      rules: {
        message: [{
          required: true,
          message: '请输入提醒内容',
          trigger: 'blur'
        }],
        remindTime: [{
          required: true,
          message: '请选择触发时间',
          trigger: 'change'
        }],
      },
      title: ''
    }
  },
  computed: {
    // 获取当前月份(1-12)
    currentMonth () {
      return this.currentDate.getMonth() + 1
    },
    // 获取今天的日期(格式: YYYY-MM-DD)
    today () {
      return this.formatDate(new Date())
    },
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate (date) {
      if (!date) return ''
      const d = new Date(date)
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${d.getFullYear()}-${month}-${day}`
    },
    // 从日期字符串中提取日
    getDate (dateString) {
      return new Date(dateString).getDate()
    },
    // 判断是否为当天
    isCurrentDay (dateString) {
      return this.formatDate(dateString) === this.today
    },
    // 判断是否为其他月份的日期
    isOtherMonth (dateString) {
      const date = new Date(dateString)
      return date.getMonth() + 1 !== this.currentMonth
    },
    // 判断是否为周末
    isWeekend (dateString) {
      const day = new Date(dateString).getDay()
      return day === 0 || day === 6
    },
    // 判断指定日期是否有事件
    hasEvent (dateString) {
      const date = this.formatDate(dateString)
      return this.events.some(event => event.startTime.split(' ')[0] === date)
    },
    // 获取指定日期的所有事件
    getEventsByDate (dateString) {
      const date = this.formatDate(dateString)
      return this.events.filter(event => event.startTime.split(' ')[0] === date)
    },
    // 获取用户日程信息
    getDatesInfo () {
      getDateAll().then((res) => {
        this.events = res.data
      })
    },
    handleRemind (item) {
      this.resetForm(item)
      if (item.remindId) {
        this.title = '修改提醒'
        getSituationById(item.remindId).then(res => {
          this.formData = res.data
        })
      }else {
        this.title = '添加提醒'
      }
    },
    submitForm(item) {
      this.$refs[`remindFrom${item.id}`][0].validate(valid => {
        if (!valid) return
        if (item.remindId){
          updateSituation(this.formData).then(res => {
            if (res.code === 200) {
              this.$message.success('修改成功')
            }
          })
        }else {
          const from = {
            scheduleId: item.id,
            remindType: 2,
            remindTime: this.formData.remindTime,
            message: this.formData.message,
          }
          addSituation(from).then(res => {
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.getDatesInfo()
              this.title = '修改提醒'
            }else if (res.code === 500) {
              this.$message.error('不可以重复添加')
            }else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    resetForm(item) {
      this.$refs[`remindFrom${item.id}`][0].resetFields()
    },
  },
  mounted () {
    // 监听窗口大小变化，用于响应式调整
    window.addEventListener('resize', () => this.$forceUpdate())
  },
  beforeDestroy () {
    // 移除事件监听器防止内存泄漏
    window.removeEventListener('resize', () => this.$forceUpdate())
  },
  created () {
    this.getDatesInfo()
  }
}
</script>

<style lang="less" scoped>
@primary-color: #409EFF;
@success-color: #67C23A;
@warning-color: #E6A23C;
@danger-color: #F56C6C;
@info-color: #909399;

.container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 日历日期单元格样式 */
.calendar-day {
  height: 60px; /* 调整高度 */
  padding: 4px; /* 调整内边距 */
  border: 1px solid #EBEEF5;
  margin: -1px 0 0 -1px;
  background: #FFF;
  transition: all 0.25s ease;

  &:hover {
    background: #F8F9FA;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transform: translateY(-1px);
    z-index: 1;
  }

  .day-number-container {
    position: relative;
    display: inline-flex;
  }

  .day-number {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px; /* 调整宽度 */
    height: 18px; /* 调整高度 */
    border-radius: 4px;
    font-weight: 500;
    font-size: 12px; /* 调整字体大小 */
    line-height: 1;

    &.current-day {
      background: @primary-color;
      color: white;
      box-shadow: 0 1px 3px rgba(64, 158, 255, 0.4);
    }

    &.other-month {
      color: #C0C4CC;
    }
  }

  .event-dot {
    position: absolute;
    bottom: -3px;
    right: -3px;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: @primary-color;
    box-shadow: 0 1px 2px rgba(64, 158, 255, 0.4);
  }

  .day-events {
    margin-top: 6px;

    .event {
      font-size: 10px; /* 调整字体大小 */
      padding: 1px 3px; /* 调整内边距 */
      margin-bottom: 2px;
      backdrop-filter: blur(2px);
      transition: transform 0.2s;

      &:hover {
        transform: scale(1.02);
      }

      &-primary {
        background: rgba(64, 158, 255, 0.12);
        color: @primary-color;
      }

      &-success {
        background: rgba(103, 194, 58, 0.12);
        color: @success-color;
      }

      &-warning {
        background: rgba(230, 162, 60, 0.12);
        color: @warning-color;
      }

      &-danger {
        background: rgba(245, 108, 108, 0.12);
        color: @danger-color;
      }
    }
  }
}

/* 卡片组件样式 */
.bg-white {
  background: #FFF;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);

  &:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;

  &--primary {
    background: @primary-color;
    border-color: @primary-color;

    &:hover {
      background: #66B1FF;
      border-color: #66B1FF;
    }
  }

  &--small {
    padding: 8px 16px;
    font-weight: 500;
  }
}

/* 动画效果 */
.animate-fade-in {
  animation: fadeIn 0.4s ease-out;

  @keyframes fadeIn {
    0% {
      opacity: 0;
      transform: translateY(12px) scale(0.98);
    }
    100% {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .container {
    padding: 16px;
  }

  .grid {
    gap: 16px !important;
  }
}
</style>
